package com.sto.stoapp.activity.sales;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.broadcast.EixtToViewManager;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.OrderManager;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.SoundManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.StoHomeActivity;

import java.util.ArrayList;
import java.util.List;

public class SalesOrderDahuiActivity extends StoHomeActivity {

    private EditText orderCauseEdit;

    private TextView orderCode;

    private DataBusinessEntity dataBusiness;

    private String Code = "", pickupNetwork = "", causeCode = "";

    private List<EditText> edit = new ArrayList<EditText>();
    private final int CAUSE_RESULT = 0xfe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sto_sales_order_dahui);
        this.setTitleBottom(R.string.order_back_piece,
                HomeBroadAction.SALES_MAN_BROAD);

        Bundle extras = getIntent().getExtras();
        initBusiData(extras.getString("busiData"));
        initWidget();
        initListen();

        EixtToViewManager.getInstance().addActivity(this);
        dataBusiness = new DataBusinessEntity();
        dataBusiness.initInsertData();
    }

    private void initWidget() {
        // String siteCode = StoFilePreference.getInstance(this).getSiteCode();
        orderCauseEdit = (EditText) findViewById(R.id.dahui_cause_text);
        orderCode = (TextView) findViewById(R.id.dahui_order_text);
        orderCode.setText(Code);
        // setTimerEdit.setSelection(siteCode.length());
        // setTimerEdit.setInputType(InputType.TYPE_NULL);
        edit.add(orderCauseEdit);
    }

    private void initBusiData(String order) {
        String[] data = order.split("\\|");
        Code = data[0];
        pickupNetwork = data[1];
    }

    /**
     * 监听控件
     */
    private void initListen() {
        orderCauseEdit.setOnClickListener(new StoOnClickListener(this) {

            @Override
            public void mHonClick(View v) {
                SelectCause();
            }
        });

        for (EditText editListener : edit) {

            /*
             * 监听EditText内容个数
             */
            editListener.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start,
                        int before, int count) {
                    if (orderCauseEdit.getText().toString().equals("")) {
                        causeCode = "";
                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start,
                        int count, int after) {
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
    }

    /**
     * 选择原因
     */
    private void SelectCause() {
        try {
            SelectTableParcel tableParcel = new SelectTableParcel();
            if (orderCauseEdit.getText().length() == 0) {
                tableParcel
                        .setSelectSql(SqlSelectTableManager.SQL_ORDER_REASON_ALL);
                tableParcel.setSelectField(new String[] {});
            } else {
                tableParcel
                        .setSelectSql(SqlSelectTableManager.SQL_ORDER_REASON_ONLY);
                tableParcel.setSelectField(new String[] {
                        orderCauseEdit.getText().toString(), "" });
            }
            tableParcel.setSelectCode("serial_number");
            tableParcel.setSelectName("record_content");

            Intent intent = new Intent(SalesOrderDahuiActivity.this,
                    StoSelectTableActivity.class);
            intent.putExtra("tableData", tableParcel);

            startActivityForResult(intent, CAUSE_RESULT);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionLog.writeLog("SelectCause", e.getMessage());
        }
    }

    private boolean addPieceRecord() {
        boolean ret;

        dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_BACK.getOpCode());
        // dataBusiness.setUser_defined3(Code);
        // dataBusiness.setDifferent_flag(Code);
        dataBusiness.setBar_code_number(Code);
        // 原因
        dataBusiness.setReason_number(causeCode);
        // 取件网点
        dataBusiness.setUser_defined4(pickupNetwork);

        dataBusiness.setUser_defined5(orderCauseEdit.getText().toString());

//        /*
//         * 修改人：mgf
//         * 修改内容:网点编号，工号以中文形式保存
//         * 修改日期：2014-02-14
//         * @see SalesManager#querySalesName、SiteFullManager#querySiteCodeName
//         */
//        // 网点编号
//        dataBusiness.setNet_code(SiteFullManager.getInstance(this).querySiteCodeName(StoFilePreference.getInstance(this)
//                .getSiteCode()));
//
//        // 工号
//        dataBusiness.setJob_number(SalesManager.getInstance(this).querySalesName(StoFilePreference.getInstance(this)
//                .getUserInfo()));
        dataBusiness.setNet_code(StoFilePreference.getInstance(this).getSiteCode());
        
        dataBusiness.setJob_number(StoFilePreference.getInstance(this).getUserCode());

        ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
                EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_BACK);
        if (ret) {
            this.addCodeNumber();
        }
        deleteOrder(Code);

        return ret;
    }

    /**
     * 删除订单
     * 
     * @param OrderCode
     */
    private void deleteOrder(String OrderCode) {
        OrderManager.getInstance(this).deleteOnly(OrderCode);
    }

    /**
     * 选择列表返回的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAUSE_RESULT && resultCode == RESULT_OK) {
            GetTableParcel courierEntity = data.getParcelableExtra("Name");
            if (courierEntity != null) {
                orderCauseEdit.setText(courierEntity.getSelectName());
                orderCauseEdit.setSelection(orderCauseEdit.length());
                causeCode = courierEntity.getSelectCode();
                if (orderCauseEdit.getText().toString().length() != 0
                        && !causeCode.equals("")) {
                    addPieceRecord();
                    SoundManager.getInstance(this).playSuccessSound();
                    /*Intent orderIntent = new Intent(BusiExitAction.SALES_MAN_ORDER_BROAD);
                    sendBroadcast(orderIntent);*/
                    EixtToViewManager.getInstance().exit();
                    //finishEx();
                } else {
                    Helper.showToast(SalesOrderDahuiActivity.this, "未选择打回原因!");
                    SoundManager.getInstance(this).playFailureSound();
                }
                // if (recvPresonCode.length() > 0)
                // destination.requestFocus();
            }
        } else {

        }
    }

    // 结束当前的activity
    //	private void finishEx() {
    //		SalesOrderDahuiActivity.this.finish();
    //	}

    @Override
    protected void onDestroy() {
    	edit.clear();
        EixtToViewManager.getInstance().clearActivity();
        super.onDestroy();
    }


}
